package com.example.zookeeper.core.impl;

import com.example.zookeeper.core.ZkCore;
import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class ZkCoreImpl implements ZkCore
{
    private final ZooKeeper zooKeeper;

    @Autowired
    public ZkCoreImpl(ZooKeeper zooKeeper)
    {
        this.zooKeeper = zooKeeper;
    }


    @Override
    public void createNode(String path, byte[] data, CreateMode createMode) throws KeeperException, InterruptedException
    {
        if (zooKeeper.exists(path, null) == null)
        {
            zooKeeper.create(path, data, ZooDefs.Ids.OPEN_ACL_UNSAFE, createMode);
        }
    }

    @Override
    public void delete(String path) throws KeeperException, InterruptedException
    {
        zooKeeper.delete(path, -1);
    }

    @Override
    public byte[] getValue(String path) throws KeeperException, InterruptedException
    {
        return zooKeeper.getData(path, false, new Stat());
    }

    @Override
    public byte[] getValue(String path, Watcher watcher) throws KeeperException, InterruptedException
    {
        return zooKeeper.getData(path, watcher, new Stat());
    }

    @Override
    public void setValue(String path, byte[] data) throws KeeperException, InterruptedException
    {
        zooKeeper.setData(path, data, -1);
    }

    @Override
    public Stat exist(String path) throws KeeperException, InterruptedException
    {
        return zooKeeper.exists(path, null);
    }


    @Override
    public List<String> getChildNodes(String path, boolean watcher) throws KeeperException, InterruptedException
    {
        return zooKeeper.getChildren(path, watcher);
    }

    @Override
    public List<String> getChildNodes(String path, Watcher watcher) throws KeeperException, InterruptedException
    {
        return zooKeeper.getChildren(path, watcher);
    }

    @Override
    public void close() throws InterruptedException
    {
        zooKeeper.close();
    }
}
